package com.whut.f2f.chat.connector;

import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Channel默认的连接实现类
 *
 * Created by null on 2017/1/25.
 */
public class DefaultConnector implements Connector {

    private final Map<String, Channel> channelMap = new ConcurrentHashMap<>();

    @Override
    public synchronized void add(String id, Channel channel) {
        channelMap.put(id, channel);
    }

    @Override
    public synchronized void remove(String id) {
        channelMap.remove(id);
    }

    @Override
    public synchronized void send(String id, String msg) {
        Channel channel = channelMap.get(id);
        channel.writeAndFlush(msg);
    }

    @Override
    public synchronized void sendAll(String msg) {
        for (Channel channel : channelMap.values()) {
            if (channel.isOpen()) {
                channel.writeAndFlush(msg);
            }
        }
    }
}
